//
//  ComposeController.swift
//  SinaBlog
//
//  Created by 李超 on 16/3/30.
//  Copyright © 2016年 lichao. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        //设置导航栏的item
        setNavigationBarItem()
        //设置子控件及其约束
        prepareUI()
        //注册通知，监听键盘的frame值改变，以便于使底部视图保持在键盘上方
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    //在界面一加载时，就弹出键盘，过程中动画有问题，应该在视图显示时做出处理
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
       // sinaTextView.inputView = sianKeyBoard
        sinaTextView.becomeFirstResponder()
    }
    
    /// 键盘frame值改变将触发的方法
    func keyboardFrameWillChange(note:NSNotification){
        
       print("\(note.userInfo)")
        let endFrame = note.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey]! as! Double
        bottomToolBar.snp_updateConstraints { (make) -> Void in
            self.bottomToolBarBottomConstraint = make.bottom.equalTo(self.view).offset(-(UIScreen.mainScreen().bounds.height - endFrame.origin.y)).constraint
        }
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
    }
    /// 注销通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    /// 用于记录底部约束的变量
    var bottomToolBarBottomConstraint:Constraint?
    /// 添加子控件
    func prepareUI(){
        //添加控件
        view.addSubview(self.sinaTextView)
        view.addSubview(self.bottomToolBar)
        //添加约束
        sinaTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        bottomToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(self.view)
            make.height.equalTo(44.0)
            //暂时与底部对齐，根据键盘的frame之进行波动
            self.bottomToolBarBottomConstraint = make.bottom.equalTo(self.view).constraint
        }
        
    }
    /// 设置左右按钮
    func setNavigationBarItem(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: Selector("dismissAction"))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", target: self, action: Selector("sendMessageToBlogAction"))
        navigationItem.rightBarButtonItem?.enabled = false
    
    }
    /// 取消按钮操作
    func dismissAction(){
        //取消作为第一响应者,避免在控制器完全退出后才退下键盘，影响体验
        self.sinaTextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
       // print("\(__FUNCTION__)")
    }
    /// 发布按钮操作
    func sendMessageToBlogAction(){
       print("\(__FUNCTION__)")
        self.sinaTextView.resignFirstResponder()
        //拼接参数
        let text = sinaTextView.emoticonString()
        let access_token = CZUserAccountTool.shareInstance.userAccount?.access_token
        let params = ["access_token":access_token! ,"status":text]
        let URLSting = "https://api.weibo.com/2/statuses/update.json"
        //发送网络请求
        CZNetworkTool.shareInstance.requestPost(URLSting, parameters: params) { (result, error) -> () in
            if error != nil{
                SVProgressHUD.showErrorWithStatus("分享失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("分享成功")
            print("\(error)")
        }
        
    }
    /// 底部按钮的相关触发操作
    func toolbarAction(){
       print("\(__FUNCTION__)")
    }
    
    func trendbuttonAction(){
         print("\(__FUNCTION__)")
    }
    
    func mentionbuttonAction(){
       print("\(__FUNCTION__)")
    }
    
    func emoticonbuttonAction(){
        //先辞去第一响应者，因为inputView被赋值后，再次赋值时暂时无效，等到下一次才有效
        sinaTextView.inputView = sinaTextView.inputView == sianKeyBoard ? nil : sianKeyBoard        
        sinaTextView.resignFirstResponder()
       // sinaTextView.inputView = sianKeyBoard
        //需要延时操作，因为辞去响应者后马上就成为第一响应者的话，键盘实际上并不会下去再上来，而是静止不动 dispatch_get_main_queue()
         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.sinaTextView.becomeFirstResponder()
        }
       //  print("\(__FUNCTION__)")
    }
    
    func addbuttonAction(){
         print("\(__FUNCTION__)")
    }
    /// 懒加载textView
    private lazy var sinaTextView:CZplacehoderTextView = {
        let textView = CZplacehoderTextView()
        textView.alwaysBounceVertical = true
        //拖动时隐藏键盘
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        textView.placeholderString = "分享点新鲜事吧。。。"
        //设置代理
        textView.delegate = self
        return textView
    }()
    /// 懒加载底部视图
    private lazy var bottomToolBar:UIToolbar = {
        let toolBar = UIToolbar()
        //先给子控件数组赋值
        toolBar.items = [UIBarButtonItem]()
        //使用数组中包字典，方便与使用，将图片与操作相关联起来，避免排序发生改变时，出现不必要的改动
        let itemSettings = [
            ["imageName": "compose_toolbar_picture","action":"toolbarAction"],
            ["imageName": "compose_trendbutton_background","action":"trendbuttonAction"],
            ["imageName": "compose_mentionbutton_background","action":"mentionbuttonAction"],
            ["imageName": "compose_emoticonbutton_background","action":"emoticonbuttonAction"],
            ["imageName": "compose_add_background","action":"addbuttonAction"]
        ]
        //遍历数组，创建对应的子控件按钮
        for dict in itemSettings{
           
            let imageName = dict["imageName"]
            let actionName = dict["action"]
            let barButton = UIBarButtonItem(imageName: imageName!, target: self, action: Selector(actionName!), Events: UIControlEvents.TouchUpInside)
            //添加子控件
            toolBar.items?.append(barButton)
            //添加弹簧
        toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        //数组的最后添加多了一个弹簧,需要删除
        toolBar.items?.removeLast()
        
        return toolBar
    }()
    //懒加载表情键盘
    private lazy var sianKeyBoard:CZEmotionKeyBoardView = {
        let keyboardView = CZEmotionKeyBoardView(frame:CGRectZero)
        keyboardView.textView = self.sinaTextView
        return keyboardView
    }()
}
/// 实现UITextview的代理方法
extension ComposeController:UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
}









